package logs

import (
	"apiManageGo/src/core/common/config"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

var logger *zap.Logger

func init() {
	// 设置日志文件的路径和其他配置
	config := config.GetConfig()
	logFilePath := config.Logs.Path
	maxSize := config.Logs.MaxSize
	maxBackups := config.Logs.MaxBackups
	maxAge := config.Logs.MaxAge

	// 配置日志的编写器，使用lumberjack进行日志滚动
	writerSyncer := zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&lumberjack.Logger{
		Filename:   logFilePath,
		MaxSize:    maxSize,
		MaxBackups: maxBackups,
		MaxAge:     maxAge,
	}))

	// 配置日志的格式
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoder := zapcore.NewJSONEncoder(encoderConfig)

	var level zap.AtomicLevel
	// 配置日志级别
	switch config.Logs.Level {
	case "debug":
		level = zap.NewAtomicLevelAt(zap.DebugLevel)
	case "info":
		level = zap.NewAtomicLevelAt(zap.InfoLevel)
	case "warn":
		level = zap.NewAtomicLevelAt(zap.WarnLevel)
	case "error":
	default:
		level = zap.NewAtomicLevelAt(zap.InfoLevel)
	}

	// 创建core
	core := zapcore.NewCore(encoder, writerSyncer, level)

	// 创建logger
	logger = zap.New(core)
	//logger = logger.WithOptions(zap.AddCaller())
	logger.Info("logger init success")
}

// 获取logger
func GetLogger() *zap.Logger {
	return logger
}

func Debug(msg string, fields ...zap.Field) {
	logger.Debug(msg, fields...)
	_ = logger.Sync()
}
func Info(msg string, fields ...zap.Field) {
	logger.Info(msg, fields...)
	_ = logger.Sync()
}
func Warn(msg string, fields ...zap.Field) {
	logger.Warn(msg, fields...)
	_ = logger.Sync()
}
func Error(msg string, fields ...zap.Field) {
	logger.Error(msg, fields...)
	_ = logger.Sync()
}
